var util = require('../../libs/util.js');
var amapFile = require('../../libs/amap-wx.js');
//获取应用实例
var app = getApp();
var amap, mapCtx;

var x, y, x1, y1, x2, y2, index, currindex, n, yy, arr1;
Page({
  data: {
    middle_height:'100%',
    latitude: 0,//纬度 
    longitude: 0,//经度
    markers: [],
    polyline: [],
    controls: [],
    "include-points": [],
    pathData: [], 
    mainx: 0,
    start: { x: 0, y: 0 }
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onShow: function () {
    var that = this;
  },
  onReady: function (e) {
    mapCtx = wx.createMapContext('map');
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({ "title": app.appName +" - 路线地图" });

    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res.latitude)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          longitude: longitude,
          latitude: latitude
        });
      }
    });

    wx.getStorage({
      key: 'path_map',
      success: function (res) {
        if (res.data) {
          var pathData = [], _pathData = res.data;
          for (var i = 0; i < _pathData.length;i++){
            _pathData[i].sort = i+1;
            if(i==0){
              _pathData[i].up = false;
            }else{
              _pathData[i].up = true;
            }
            if (i == _pathData.length -1) {
              _pathData[i].down = false;
            } else {
              _pathData[i].down = true;
            }
            pathData.push(_pathData[i])
          }
          that.setData({
            pathData: pathData
          });
          arr1 = pathData;
          var systemInfo = wx.getSystemInfoSync();
          that.setData({
            middle_height: (systemInfo.windowHeight - 50 - (pathData.length > 5 ? 5 : pathData.length) * 36) + 'px',
            pathPageHeight: ((pathData.length > 5 ? 5 : pathData.length) * 36) + 'px'
          });

          that.initMap();
        }
      }
    });
  },
  initMap:function(){
    var that = this;
    amap = new amapFile.AMapWX({ key: 'a404e7cb1dcd34bb623e46fc3e46691e' });
    var pathData = that.data.pathData,markers = [], lalt = [],marker_img;
    for (var i = 0; i < pathData.length;i++){
      if (pathData[i].type == 'warehouse'){
        marker_img = "/images/warehouse.png";
      }else{
        marker_img = "/images/shop.png";
      }
      var m_number = Number(markers.length + 1);
      markers.push({
        id: m_number,
        title: pathData[i].name,
        iconPath: "/images/number/" + m_number+".png",
        width: 20,
        height: 20,
        latitude: pathData[i].latitude,
        longitude: pathData[i].longitude
      });
      lalt.push({
        latitude: pathData[i].latitude,
        longitude: pathData[i].longitude
      });
    }

    that.setData({
      markers: markers,
      lalt: lalt
    });

    this.getDrivingRoute();

    try{
      mapCtx.includePoints({
        padding: [20],
        points: that.data.lalt
      })
    }catch(e){}

  },
  regionchange:function(){
    
  },
  getDrivingRoute:function(){
    var that = this;
    var pathData = that.data.pathData;

    var markers = [], lalt = [];

    var firstPOI, lastPOI, waypoints = new Array(), w_index = 0;
    for (var i = 0; i < pathData.length; i++) {
      if (i == 0) {
        firstPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else if (i == pathData.length - 1) {
        lastPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else {
        waypoints[w_index] = pathData[i].longitude + ',' + pathData[i].latitude;
        w_index++;
      }

      markers.push({
        id: i+1,
        title: pathData[i].name,
        iconPath: "/images/number/" + (i + 1) + ".png",
        width: 20,
        height: 20,
        latitude: pathData[i].latitude,
        longitude: pathData[i].longitude
      });
      lalt.push({
        latitude: pathData[i].latitude,
        longitude: pathData[i].longitude
      });
    }
    that.setData({
      markers: markers,
      lalt: lalt
    });

    amap.getDrivingRoute({
      origin: firstPOI,
      destination: lastPOI,
      waypoints: waypoints.join(";"),
      strategy: 4,
      province: '粤',
      number: 'B5Q31Z',
      success: function (data) {
        var points = [];
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          var steps = data.paths[0].steps;
          for (var i = 0; i < steps.length; i++) {
            var poLen = steps[i].polyline.split(';');
            for (var j = 0; j < poLen.length; j++) {
              points.push({
                longitude: parseFloat(poLen[j].split(',')[0]),
                latitude: parseFloat(poLen[j].split(',')[1])
              })
            }
          }
        }
        that.setData({
          polyline: [{
            points: points,
            color: "#0091ff",
            width: 6
          }]
        });
        if (data.paths[0] && data.paths[0].distance) {
          var duration = Number(data.paths[0].duration) + pathData.length * 30*60;
          var hourToTime = util.hourToTime(duration);
          that.setData({
            distance: (data.paths[0].distance / 1000).toFixed(1),
            duration: Number(duration).toFixed(2),
            duration_hour: hourToTime.hour,
            duration_minute: hourToTime.minute
          });
        }
        mapCtx.includePoints({
          padding: [10],
          points: that.data.lalt
        })
      },
      fail: function (info) {

      }
    })

  },
  pl_item_down:function(e){console.log(e)
    var id = e.currentTarget.dataset.id, sort = e.currentTarget.dataset.sort;
    var pathData = this.data.pathData, _pathData = [], change_item = '';
    for (var i = 0; i < pathData.length; i++) {
      if (pathData[i].sort == sort) {
        change_item = pathData[i];
      } else{
        if (pathData[i].sort == sort + 1) {
          _pathData.push(pathData[i]);
          _pathData.push(change_item);
        } else {
          _pathData.push(pathData[i]);
        }
      }
    };
    for (var i = 0; i < _pathData.length; i++) {
      _pathData[i].sort = i + 1;
      if (i == 0) {
        _pathData[i].up = false;
      } else {
        _pathData[i].up = true;
      }
      if (i == _pathData.length - 1) {
        _pathData[i].down = false;
      } else {
        _pathData[i].down = true;
      }
    }
    this.setData({
      pathData: _pathData
    });
    this.getDrivingRoute();
    wx.setStorage({
      key: "path_map",
      data: this.data.pathData
    });
  },
  pl_item_up: function (e) {
    var id = e.currentTarget.dataset.id, sort = e.currentTarget.dataset.sort;
    var pathData = this.data.pathData, _pathData = [], change_item = '';
    for (var i = 0; i < pathData.length; i++) {
      if (pathData[i].sort == sort - 1) {
        _pathData.push(pathData[i+1]);
        _pathData.push(pathData[i]);
      } else if (pathData[i].sort == sort){

      } else {
        _pathData.push(pathData[i]);
      }
    };
    for (var i = 0; i < _pathData.length; i++) {
      _pathData[i].sort = i + 1;
      if (i == 0) {
        _pathData[i].up = false;
      } else {
        _pathData[i].up = true;
      }
      if (i == _pathData.length - 1) {
        _pathData[i].down = false;
      } else {
        _pathData[i].down = true;
      }
    }
    this.setData({
      pathData: _pathData
    });
    this.getDrivingRoute();
    wx.setStorage({
      key: "path_map",
      data: this.data.pathData
    });
  },
  backToDelivery:function(){
    wx.navigateBack({
      delta: 1
    })
  }
})
